package com.yupi.yupao.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.yupi.yupao.common.BaseContext;
import com.yupi.yupao.common.BaseResponse;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.common.ResultUtils;
import com.yupi.yupao.config.RedisConfig;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.Invitation;
import com.yupi.yupao.model.domain.Team;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.UserInvitation;
import com.yupi.yupao.model.dto.InvitationDTO;
import com.yupi.yupao.model.vo.IsReadMsgVO;
import com.yupi.yupao.service.TeamService;
import com.yupi.yupao.service.UserService;
import com.yupi.yupao.websocket.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;


/**
 *
 * @description
 * @date
 */
@Api(tags = "WebSocket-test")
@RestController()
@RequestMapping("/ws")
@Slf4j
public class OrderNotificationWebSocketController {

    @Resource
    private WebSocketServer webSocketServer;
    @Resource
    private TeamService teamService;
    @Resource
    private RedisTemplate<String, Invitation> redisTemplate;
    @Resource
    private RedisConfig redisConfig;
    @Resource
    private UserService userService;

    //发送消息

    /**
     *

     * @return
     * @throws RuntimeException
     */
    @ApiOperation("发送邀请通知")
    @PostMapping(value = "/sendInvitation")
    public BaseResponse<String> sendInvitation(@RequestBody InvitationDTO invitationDTO) throws RuntimeException{
        Long senderId = BaseContext.getCurrentId();//登录人id
        if(senderId.equals(invitationDTO.getUserId())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不能邀请自己");
        }
        String key = "team:invites:" + invitationDTO.getUserId();
        String uId = String.valueOf(invitationDTO.getUserId());
        //读取历史消息
        // 检查用户是否已连接
        if (webSocketServer.isUserConnected(String.valueOf(senderId) )) {
//             用户已连接，发送消息
//            webSocketServer.sendToClient(uId, msg);
            Team team = teamService.getById(invitationDTO.getTeamId());
            if(team==null){
                throw new BusinessException(ErrorCode.NULL_TEAM);
            }
            Gson gson = new Gson();
            String teamStr = gson.toJson(team);
            Long loginuserId = BaseContext.getCurrentId();
            User user = userService.getById(loginuserId);
            UserInvitation userInvitation = new UserInvitation();
            userInvitation.setId(invitationDTO.getUserId());
            userInvitation.setUsername(user.getUsername());
            Invitation invitation = new Invitation(invitationDTO.getUserId(), teamStr, false,userInvitation,new Date());

            String messageId = String.valueOf(System.currentTimeMillis());
//            teamService.saveInvitation(senderId,userId,teamStr);
            //发送成功后存redis--历史消息
            webSocketServer.sendToClient(String.valueOf(invitationDTO.getUserId()),teamStr);

            redisTemplate.opsForHash().put(key,String.valueOf(invitationDTO.getTeamId()),invitation);
            redisTemplate.expire(key, Duration.ofHours(24));
            return ResultUtils.success("发送成功");
        } else {
            // 用户未连接
            throw  new BusinessException(ErrorCode.WS_NOT_CONNECT,"用户未连接");
        }
    }
    @GetMapping("/getUnReadMsg")
    public BaseResponse<List<IsReadMsgVO>> getUnreadMsg(){
        List<IsReadMsgVO> isReadMsgList=new ArrayList<>();
        Long userId = BaseContext.getCurrentId();
        String key = "team:invites:" + userId;
        Map<Object, Object> map = redisTemplate.opsForHash().entries(key);
        Map<Long,Invitation> unReadMsgMap=new HashMap<>();
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            Long messageId = Long.valueOf((String) entry.getKey()); // 将key转换为Long类型
            Invitation invitation = (Invitation) entry.getValue(); // 将value转换为Invitation类型
            unReadMsgMap.put(messageId, invitation);
        }
        Gson gson = new Gson();
        for (Map.Entry<Long,Invitation> item: unReadMsgMap.entrySet()) {
            log.info("item:"+item);
            Team team = gson.fromJson(item.getValue().getTeamInfo(), Team.class);
            IsReadMsgVO isReadMsgVO = new IsReadMsgVO(item.getValue().getReceiverId(), team, item.getValue().isRead(),item.getValue().getUser(), item.getValue().getInvitationTime());
            isReadMsgList.add(isReadMsgVO);
        }
//        List<Invitation> collect = unReadMsgMap.values().stream().collect(Collectors.toList());
        return ResultUtils.success(isReadMsgList);
    }
    @GetMapping("markMsg/{teamId}")
    public BaseResponse<String> markMsgAsRead(@PathVariable(value = "teamId") Long teamId){
        Boolean read = teamService.markInvitationsAsRead(teamId);
        return ResultUtils.success("已读");

    }
}
